import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/components/image_picker_widget.dart';
import 'package:kxy_flutter_app/components/loading_dialog.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/break_rule.dart';
import 'package:kxy_flutter_app/view/course/course_item_widget.dart';
import 'package:kxy_flutter_app/view/examination/template/official_exam_widget.dart';

class BreakRuleDetailView extends StatefulWidget {
  final String id;

  const BreakRuleDetailView({Key key, @required this.id}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return BreakRuleDetailViewState();
  }
}

class BreakRuleDetailViewState extends State<BreakRuleDetailView> {
  BreakRule rule;
  Future loadFuture;
  LoadingDialog loading;
  var format = new DateFormat('yyyy-MM-dd');

  @override
  void initState() {
    loading = new LoadingDialog(context);
    loadFuture = loadBreakRule();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('违章内容')),
      body: FutureBuilder(
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
        future: loadFuture,
      ),
    );
  }

  Widget body() {
    return ListView(
      padding: EdgeInsets.symmetric(vertical: 10),
      children: [
        fieldItem(
          field: '培训通知单',
          child: ImagePickerWidget(initUrl: rule.trainNoticeUrl),
        ),
        fieldItem(
          field: '处罚单',
          child: ImagePickerWidget(initUrl: rule.punishNoticeUrl),
        ),
        fieldItem(
          field: '三违记录',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('违反时间 :  ${rule.breakRuleTime ?? ''}', style: TextStyle(height: 1.5)),
              Text('违反原因 :  ${rule.reason ?? ''}', style: TextStyle(height: 1.5)),
              Text('违反规则 :  ${rule.breakRule ?? ''}', style: TextStyle(height: 1.5)),
              Text('处罚结果 :  ${rule.punishResult ?? ''}', style: TextStyle(height: 1.5)),
              Text('处罚等级 :  ${rule.punishLevel ?? ''}', style: TextStyle(height: 1.5)),
            ],
          ),
        ),
        fieldItem(
          field: '三违考试',
          bgColor: Color.fromRGBO(240, 240, 240, 1),
          child: OfficialExamWidget(
            examList: rule.examList,
            refresh: () => loadBreakRule(),
          ),
        ),
        fieldItem(
          field: '学习内容',
          child: Column(
            children: rule.courseList.map((course) {
              return CourseItemWidget(
                course: course,
                callback: (courseId) => loadBreakRule(),
              );
            }).toList(),
          ),
        ),
        fieldItem(
          field: '检讨书(可上传2M以内图片)',
          child: ImagePickerWidget(
            initUrl: rule.remorseLetterUrl,
            uploaded: (url) => updateLetterUrl(url),
          ),
        ),
      ],
    );
  }

  Widget fieldItem({String field, Widget child, Color bgColor = Colors.white}) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(0, 0, 0, 0.07),
            blurRadius: 3,
          ),
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.black12,
                  width: 0.5,
                ),
              ),
            ),
            child: Text(
              field,
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(5, 0, 5, 5),
            decoration: BoxDecoration(
              color: bgColor,
            ),
            padding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
            child: child,
          ),
        ],
      ),
    );
  }

  Future updateLetterUrl(String url) async {
    loading.show();
    var res = await Http.instance.post(
      '/usercenter-app/breakrule/updateRemorseLetter',
      params: {
        'id': rule.id,
        'remorseLetterUrl': url,
      },
    );
    loading.dismiss();
    if (res.code == 200) {
      Fluttertoast.showToast(msg: '上传成功');
      setState(() {
        rule.remorseLetterUrl = url;
      });
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }

  Future loadBreakRule() async {
    var res = await Http.instance.post('/usercenter-app/breakrule/info/${widget.id}');
    setState(() {
      rule = BreakRule.fromJson(res.data);
    });
  }
}
